﻿using System;
using System.Collections.Generic;
using System.Linq;
using mBlog.Models;
using mBlog.Data;
using mBlog.Extensions;

namespace mBlog.Services
{
    public class CategoryService : ICategoryService
    {

        private mBlogContext blogContext;

        public CategoryService(mBlogContext context)
        {
            this.blogContext = context;
        }

        public Category Single(int id)
        {
            return blogContext.Categories.SingleOrDefault(c => c.Id == id)
                    .MapTo<Category>();
        }

        public Category Single(string urlName)
        {
            return blogContext.Categories.SingleOrDefault(c => c.UrlName == urlName)
                    .MapTo<Category>();
        }


        public IList<Category> Get()
        {
            return blogContext.Categories.Where(c => c.IsActive)
                    .AsEnumerable()
                    .MapTo<Category>()
                    .ToList();
        }

        public int GetPostTotalUnderCategory(string categoryUrlName)
        {
            var category = blogContext.Categories.Include("Posts").Single(c => c.UrlName == categoryUrlName);

            return category.Posts.Count();
        }

        public int Count()
        {
            return blogContext.Categories.Count();
        }


        public void Update(Category category)
        {
            var cat = blogContext.Categories.Single(c => c.Id == category.ID);
            if(cat != null )
            {
                cat = category.MapTo<Data.Entities.Category>();

                blogContext.SaveChanges();
            }
        }


        public void Add(Category category)
        {
            var cat = blogContext.Categories.SingleOrDefault(c => c.UrlName == category.UrlName);
            if (cat == null)
            {
                var categoryEntity = new Data.Entities.Category();
                category.MapPropertiesToInstance(categoryEntity);
                blogContext.Categories.Add(categoryEntity);
                blogContext.SaveChanges();
            }
        }

        public void Delete(int categoryId)
        {
            var cat = blogContext.Categories.SingleOrDefault(c => c.Id == categoryId);

            blogContext.Categories.Remove(cat);

            blogContext.SaveChanges();
        }
    }
}
